from authlib.integrations.flask_client import OAuth
from authlib.integrations.requests_client import OAuth2Session

from app.config import Config

__oauth = None

def allow_insecure_http(client):
    """禁用 HTTPS 验证"""
    client.session.verify = False
    return client


def init_authlib(app):
    """

    :param app:
    """
    global __oauth
    __oauth = OAuth(app)
    __oauth.register(
        name='github',
        client_id=Config.GITHUB_CLIENT_ID,
        client_secret=Config.GITHUB_CLIENT_SECRET,
        access_token_url='https://github.com/login/oauth/access_token',
        access_token_params=None,
        authorize_url='https://github.com/login/oauth/authorize',
        authorize_params=None,
        api_base_url='https://api.github.com/',
        client_kwargs={'scope': 'user:email'},
    )

    __oauth.register(
        name='google',  # 客户端名称（需与路由参数一致）
        client_id=Config.GOOGLE_CLIENT_ID,
        client_secret=Config.GOOGLE_CLIENT_SECRET,
        access_token_url='https://oauth2.googleapis.com/token',  # Google的令牌端点
        authorize_url='https://accounts.google.com/o/oauth2/v2/auth',  # 授权端点
        api_base_url='https://www.googleapis.com/auth/drive.metadata.readonly',  # API基础URL
        # 关键：指定 OpenID Connect 元数据地址
        server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
        client_kwargs={
            'scope': 'openid email profile',  # 请求的权限范围
            # 可选参数（推荐添加）
            'authorize_params': {
                'access_type': 'offline',  # 允许获取刷新令牌
                'prompt': 'consent'  # 强制用户重新授权
            }
        }
    )

    __oauth.register(
        name='huomoe0',  # 客户端名称（需与路由参数一致）
        client_id=Config.HUOMOE0_CLIENT_ID,
        client_secret=Config.HUOMOE0_CLIENT_SECRET,
        access_token_url='http://127.0.0.1:8080/oauth/token',  # Google的令牌端点
        authorize_url='http://127.0.0.1:8080/oauth/authorize',  # 授权端点
        client_kwargs={
            'scope': 'profile',
            # 关键：允许 HTTP 传输（仅限开发环境）
            # 'code_challenge_method': 'S256',  # 如果使用 PKCE
            # 'token_endpoint_auth_method': 'client_secret_basic',
        },
        # # 禁用 HTTPS 检查
        # compliance_fix=allow_insecure_http
    )


def get_oauth():
    global __oauth
    return __oauth
